﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Taobao.common;

namespace Taobao.Saver
{
    /// <summary>
    /// 負責檢查重複跟加入或更新數據
    /// </summary>
    public partial class Manager:BSaver
    {
        public Manager()
        #region >><<
        {

        }

        public bool isDispose { get; protected set; }
        public void Dispose()
        {
            Stop();
        }
        #endregion

        public bool isStart { get; set; }
        #region >>Start<<
        public void Start()
        {
            isStart = true;
            initCTimer();
            initCheckItem();
            initAddItem();
            //intHandler();
            initCTimer();
        }

        public void Stop()
        {
            isStart = false;
            disCTimer();
            disCheckItem();
            disOddsAdd();
            disCTimer();
        }
        #endregion

        private System.Timers.Timer CTimer;
        #region >><<
        private void initCTimer()
        {
            CTimer = new System.Timers.Timer(1000 * 60 * 5);
            CTimer.Elapsed += new System.Timers.ElapsedEventHandler(CTimer_Elapsed);
            CTimer.Start();
        }

        private void disCTimer()
        {
            if (CTimer != null)
                CTimer.Stop();
            CTimer = null;
        }

        private void CTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (isDispose) return;

            if (CheckItem != null)
            {
                CheckItem.TrimExcess();
            }

            if (ADDtoItems != null)
            {
                Monitor.Enter(ADDtoItems);
                //foreach (WebsiteOddsItem item in ADDtoOdds.Values)
                //{
                //    item.TrimExcess();
                //}
                Monitor.Exit(ADDtoItems);
            }
        }
        #endregion

        protected OddsCheckItem CheckItem = null;
        protected virtual void initCheckItem()
        #region >><<
        {
            CheckItem = new OddsCheckItem(this);
            isDuplicateCheck = false;
        }
        private void disCheckItem()
        {
            if (CheckItem != null)
                CheckItem.Dispose();
            CheckItem = null;
        }
        #endregion

        public void ADD(WEBsite website, SPORTType sporttype, List<TeamRecord> plst)
        {
            if (isDispose || plst == null || plst.Count == 0) return;
            CheckItem.ADD(website, sporttype, plst);
        }

        #region >>AddItem<<
        private System.Threading.Thread addThread;
        private System.Threading.ManualResetEvent _addEvent;
        private Dictionary<Store, WebsiteOddsItem> ADDtoItems;

        private void initAddItem()
        #region >><<
        {
            if (ADDtoItems == null)
                ADDtoItems = new Dictionary<WEBsite, WebsiteOddsItem>();

            if (_addEvent == null)
                _addEvent = new System.Threading.ManualResetEvent(false);

            if (addThread == null || !addThread.IsAlive)
            {
                addThread = new System.Threading.Thread(new System.Threading.ThreadStart(AddItemRun));
                addThread.IsBackground = true;
                addThread.Start();
            }
        }

        private void disOddsAdd()
        {
            if (ADDtoItems != null)
                ADDtoItems.Clear();
            ADDtoItems = null;

            if (_addEvent != null)
                _addEvent.Close();
            _addEvent = null;

            if (addThread != null && !addThread.IsAlive)
            {
                try
                {
                    addThread.Abort();
                }
                catch (System.Threading.ThreadAbortException) { }
            }

        }

        #endregion

        public void AddItem(SHOPArgs args)
        #region >><<
        {
            try
            {
                if (isDispose || !isStart || ADDtoItems == null || plst == null || plst.Count == 0) return;
                initAddItem();

                if (!ADDtoItems.ContainsKey(website))
                {
                    ADDtoItems.Add(website, new WebsiteOddsItem());
                    ADDtoItems[website].Website = website;
                }
                ADDtoItems[website].AddRange(plst);

                _addEvent.Set();
            }
            catch (ArgumentNullException ex) { WriteLine(ex.Message); }
        }
        #endregion

        private void AddItemRun()
        #region >><<
        {
            while (!isDispose)
            {
                try
                {
                    if (_addEvent == null || ADDtoItems == null) break; else _addEvent.WaitOne();

                    if (ADDtoItems.Count == 0)
                        _addEvent.Reset();
                    else
                    #region >><<
                    {
                        bool brun = false;

                        try
                        {
                            List<WebsiteOddsItem> lst1 = (from c in ADDtoItems.Values select c).ToList();

                            for (int ii = 0; ii < lst1.Count; ii++)
                            {
                                WebsiteOddsItem item = lst1[ii];
                                if (item.Count > 0)
                                #region >><<
                                {
                                    brun = true;

                                    WebsiteOddsItem item2 = new WebsiteOddsItem();
                                    item2.Website = item.Website;
                                    if (item.Count > RunSQLCount)
                                        item2.AddRange(item.GetRange(0, RunSQLCount));
                                    else
                                        item2.AddRange(item.GetRange(0, item.Count));

                                    if (item2.Count > 0)
                                    {
                                        SaveItem item3;
                                        //if (OddsSaveItem.Next(item.Name, out item3))
                                        //{//這裡會偶而出現、空內容而自爆
                                        //    item3.CurrentItem = item2;
                                        //    item.RemoveRange(0, item2.Count);
                                        //}
                                    }
                                }
                                #endregion
                            }
                        }
                        catch (ArgumentException ex) { WriteLine(">>" + _className + "\r\n" + ex.Message); }
                        catch (NullReferenceException ex) { WriteLine(">>" + _className + "\r\n" + ex.Message); }

                        if (!brun)
                            _addEvent.Reset();
                        else
                            System.Threading.Thread.Sleep(100);
                    }
                    #endregion

                    System.Threading.Thread.Sleep(10);

                }
                catch (ArgumentException ex)
                {
                    WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + _className + "\r\n" + ex.Message);
                }
            }
        }
        #endregion
        #endregion

      

        public static int RunSQLCount { get { return _RunSQLCount; } set { _RunSQLCount = value; } }
        private static int _RunSQLCount = 100;

        /// <summary>
        /// 是否再次檢查重複
        /// </summary>
        public static bool isDuplicateCheck { get; set; }

        #region >><<
        public static event EventHandler AddNewOddsEvent;
        public static void OnAddNewOdds(string msg)
        {
            if (AddNewOddsEvent == null) return;
            AddNewOddsEvent(null, new OUtl.MessageEventArgs(msg));
        }

        #endregion
    }
}